package net.protocol.object;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import net.protocol.Protocol;

public class ObjectProtocol implements Protocol {

	@Override
	public void sendPorts(OutputStream out, ArrayList<Integer> ports) throws IOException {
		sendObject(out,ports);
	}
	
	private void sendObject(OutputStream out, Object toSend) throws IOException{
		ObjectOutputStream oStream = new ObjectOutputStream(out);
		oStream.writeObject(toSend);
		oStream.flush();
	}
	
	private Object receiveObject(InputStream in) throws IOException{
		ObjectInputStream oStream = new ObjectInputStream(in);
		try {
			return oStream.readObject();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Protocol create() {
		return new ObjectProtocol();
	}

	@Override
	public int recievePort(InputStream in) throws IOException {
		Object o = receiveObject(in);
		if(o == null)
			return 0;
		return (Integer) o;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ArrayList<Integer> recievePorts(InputStream in) throws IOException {
		return (ArrayList<Integer>)receiveObject(in);
	}

	@Override
	public void sendPort(OutputStream out, Integer port) throws IOException {
		sendObject(out, port);
	}

	@Override
	public void sendData(OutputStream out, Object data) throws IOException {
		sendObject(out,data);
	}

	@Override
	public Object recieveData(InputStream in) throws IOException {
		return receiveObject(in);
	}
	
}
